package com.kgc.web;

import com.kgc.dao.UserPaymentDao;
import com.kgc.entity.UserPayment;
import com.kgc.untils.AlipayConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "PayServlet", value = "/PayServlet")
public class PayServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String opt = request.getParameter("opt");
        UserPaymentDao userPaymentDao = new UserPaymentDao();
        HttpSession session = request.getSession();
        if ("pay".equals(opt)) {
            // 1.查询支付订单
            int id = Integer.parseInt(request.getParameter("id"));
            session.setAttribute("orderId", id);
            UserPayment userPayment = userPaymentDao.selectUserPaymentById(id);
            String result = AlipayConfig.aliPay(userPayment);
            System.out.println("result = " + result);
            response.getWriter().print(result);
        } else if ("status".equals(opt)) {
            //确认支付
            Object orderId = session.getAttribute("orderId");
            if (orderId != null) {
                int id = (int) orderId;
                userPaymentDao.updateStatus(id);
                response.sendRedirect("/page/user/pay_success.jsp");
            }


        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
